import numpy as np
from SpcDriver.protocol import SpcProtocol
import threading
from SpcDriver.spcserial import SpcSerial
import time

def demoTxTask(argm = None):
    print("run demoTxTask\n")
    global uart
    print(uart.port)

    data = ''.encode('utf-8')
    addrs = 0x02
    AckDti = 0
    endflag = '\r\n'.encode('utf-8')


    while True:
        print("\n")
        key = ord(input("please input a key:"))
        print(key, end='\n')
        if(key == ord('1')):
            print("send ack")
            data += '>'.encode('utf-8')

            data += chr((addrs << 5) | AckDti).encode('utf-8')

            data += chr(1).encode('utf-8')

            data += chr(2).encode('utf-8')

            data += endflag
            print(uart.name + 'send >> ' + str(data.hex()))
        else:
            print("input error")
        time.sleep(1)
    return


if __name__ == "__main__":
    global uart
    r_data = "".encode("utf-8")
    uart = SpcSerial("serial1", "/dev/ttyAMA0", baudrate = 115200)
    
    uart.Open()
    
    demotask = threading.Thread(target=demoTxTask, name = "demoTxTask", args=[])
    demotask.start()

    while True:
        size = 0
        print("run main\n")
        while size == 0:
            (r_data, size) = uart.ReadLine()
        if size > 0:
            print("Get {0} byte >>".format(size), end=' ')
            for d in r_data:
                print(d,end=' ')
            print("\n")
        time.sleep(1)
        continue

    uart.Close()
    uart.__del__()
